import axios from 'axios'
import { ElMessage } from 'element-plus'
import { diffTokenExpired } from '@/utils/auth'
import store from '@/store'
const service = axios.create({
  baseURL: 'http://127.0.0.1:5000/',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      if (diffTokenExpired()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token过期'))
      } else {
        config.headers.Authorization = localStorage.getItem('token')
      }
    }
    return config
  },
  error => {
    return Promise.reject(new Error(error))
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // 直接返回数据，不再检查 code
    return res
  },
  error => {
    // 错误处理
    const message = error.response?.data?.message || error.message || '请求失败'
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default service
